package com.hjq.controller;

import com.hjq.pojo.Result;
import com.hjq.pojo.User;
import com.hjq.service.UserService;
import com.hjq.utils.JwtUtil;
import com.hjq.utils.Md5Util;
import com.hjq.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Validated
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        log.info("用户注册，参数为{},{}", username, password);
        User user = userService.getByUserName(username);
        if (user == null) {
            userService.register(username, password);
            return Result.success();
        } else {
            return Result.error("用户名已被占用");
        }
    }

    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        log.info("用户登录，参数为{}, {}", username, password);
        User user = userService.getByUserName(username);
        if (user == null) {
            return Result.error("用户名不存在！");
        }

        // 用户登录成功
        if (Md5Util.getMD5String(password).equals(user.getPassword())) {
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id", user.getId());
            claims.put("username", user.getUsername());
            String token = JwtUtil.genToken(claims);

            // 将token存储到redis中，既作为键，也作为值
            ValueOperations<String, String> op = stringRedisTemplate.opsForValue();
            op.set(token, token, 1, TimeUnit.HOURS);

            return Result.success(token);
        }

        return Result.error("密码错误！");
    }

    @GetMapping("/userInfo")
    public Result<User> userInfo() {
        log.info("获取用户详细信息");
        HashMap<String, Object> claims = ThreadLocalUtil.get();
        User user = userService.getByUserName((String) claims.get("username"));
        return Result.success(user);
    }

    @PutMapping("/update")
    // 使用@Validated对User类中的成员变量格式进行校验
    public Result update(@RequestBody @Validated User user) {
        log.info("更新用户信息，参数为{}", user);
        userService.update(user);
        return Result.success();
    }

    @PatchMapping("/updateAvatar")
    // @URL注解表示参数校验需要满足是一个合法的url
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        log.info("更新用户头像，参数为用户头像的url：{}", avatarUrl);
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    @PatchMapping("updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> map, @RequestHeader("Authorization") String token) {
        log.info("更新用户密码，参数为旧密码、新密码与确认密码：{}", map);
        String oldPwd = map.get("old_pwd");
        String newPwd = map.get("new_pwd");
        String rePwd = map.get("re_pwd");

        //参数校验
        //非空校验
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("参数为空");
        }

        //原密码正确性校验
        HashMap<String, Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        String password = userService.getByUserName(username).getPassword();
        if (!Md5Util.getMD5String(oldPwd).equals(password)) {
            return Result.error("原密码错误");
        }

        //新密码校验
        if (!newPwd.equals(rePwd)) {
            return Result.error("两次输入的密码不一致");
        }

        userService.updatePwd(username, newPwd);

        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }
}
